package com.bulls.dsp.common.util;


import com.bulls.dsp.exception.ExcelException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;

public class ExcelHelper {

    @SuppressWarnings("unchecked")
    public static <T> Workbook createWorkBook(String sheetName, String[] headers, Collection<T> source) {

        //创建Workbook对象（这一个对象代表着对应的一个Excel文件）
        //HSSFWorkbook表示以xls为后缀名的文件
        Workbook wb = new HSSFWorkbook();

        //创建Sheet并给名字(表示Excel的一个Sheet)
        Sheet sheet = wb.createSheet(sheetName);

        // 产生表格标题行
        HSSFRow row = (HSSFRow) sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据，产生数据行
        Iterator<T> it = source.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;

            row = (HSSFRow) sheet.createRow(index);
            T t = it.next();

            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {

                HSSFCell cell = row.createCell(i);

                Field field = fields[i];

                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);

                Class tCls = t.getClass();
                try {
                    Method getMethod = tCls.getMethod(getMethodName);
                    Object value = getMethod.invoke(t);

                    cell.setCellValue(String.valueOf(value));
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    throw new ExcelException("导出excel异常");
                }

            }
        }
        return wb;
    }
}